package com.yxjx.duoxue.payment;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.customview.YxListView;
import com.yxjx.duoxue.datamodel.DMOrder;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.datamodel.config.ConfigRefundReasonDTS;
import com.yxjx.duoxue.datamodel.config.ConfigRefundTypeDTS;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;

public class RefundRequestActivity extends BaseActionBarActivity {
	
	private static final int MSG_LOAD_INFO_DONE = 1;
	private static final int MSG_REFUND_DONE = 2;
	
	private ProgressDialog dialog;
	private TextView submit;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_LOAD_INFO_DONE:
				dismissDialogInternal();
				submit.setEnabled(true);
				fillSheet();
				initTypesAndReasons();
				break;
			case MSG_REFUND_DONE:
				dismissDialogInternal();
				ResponseObject code = (ResponseObject) msg.obj;
				if (code.getCode() == MsgCode.SUCCESS) {
					UIHelper.showTips(submit, "申请退款成功");
					setResult(RESULT_OK);
					RefundRequestActivity.this.finish();
				} else {
					UIHelper.showTips(submit, "申请退款失败，" + MsgCode.descFor(code));
				}
			default:
				break;
			}
		};
	};

	private DMOrder order;
	private TypesAdapter typesAdapter;

	private ReasonsAdapter reasonsAdapter;
	
	private void initTypesAndReasons() {
		YxListView listTypes = (YxListView) findViewById(R.id.refund_type);
		typesAdapter = new TypesAdapter();
		listTypes.setAdapter(typesAdapter);
		YxListView listReasons = (YxListView) findViewById(R.id.refund_reason);
		reasonsAdapter = new ReasonsAdapter();
		listReasons.setAdapter(reasonsAdapter);
		listReasons.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Boolean status = reasonsAdapter.getCheckStatus().get(arg2);
				reasonsAdapter.getCheckStatus().set(arg2, !status);
				reasonsAdapter.notifyDataSetInvalidated();
				
			}
		});
	}

	protected void fillSheet() {
		if (order != null) {
			UIHelper.setText((TextView) findViewById(R.id.order_course_name), order.getCourse().getCourseName());
			UIHelper.setText((TextView) findViewById(R.id.order_product_name), order.getProductName());
			UIHelper.setText((TextView) findViewById(R.id.order_refund_price), order.getPayPrice() + "元");
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_request_refund);
		customizeActionBarTitle("申请退款");
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		customizeUI();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(Yx.KEY_ORDER_OBJECT, order);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (getIntent() == null) {
			return;
		} else {
			Serializable savedObject = savedInstanceState.getSerializable(Yx.KEY_ORDER_OBJECT);
			if (savedObject != null) {
				getIntent().putExtra(Yx.KEY_ORDER_OBJECT, savedObject);
			}
		}
	}
	
	private void customizeUI() {
		
		if (getIntent() == null || getIntent().getExtras() == null) {
			finish();
			return;
		}
		
		order = (DMOrder) getIntent().getExtras().getSerializable(Yx.KEY_ORDER_OBJECT);
		
		submit = (TextView) findViewById(R.id.submit);
		submit.setEnabled(false);
		
		Globals data = Globals.getInstance(this);
		if (data.getRefundReasons() == null || data.getRefundTypes() == null) {
			Thread thread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						ResponseObject code = NwUtils.requestRefundInfo(getApplicationContext());
						if (code.getCode() == MsgCode.SUCCESS) {
							mHandler.sendEmptyMessage(MSG_LOAD_INFO_DONE);
							return;
						}
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (ParseException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
			thread.start();
			dialog = MyProgressDialog.show(this, "", "加载中...");
		} else {
			mHandler.sendEmptyMessage(MSG_LOAD_INFO_DONE);
		}
	}
	
	class TypesAdapter extends BaseAdapter {
		
		ArrayList<ConfigRefundTypeDTS> types = Globals.getInstance(getApplicationContext()).getRefundTypes();
		private ArrayList<Boolean> checkStatus = new ArrayList<Boolean>();
		
		public TypesAdapter() {
			for (ConfigRefundTypeDTS type : types) {
				checkStatus.add(true);
			}
		}
		
		@Override
		public int getCount() {
			return types == null ? 0 : types.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_refund_types_list, null);
			} else {
				ret = arg1;
			}
			ret.findViewById(R.id.indicator).setSelected(checkStatus.get(arg0));
			UIHelper.setText(ret, R.id.text, types.get(arg0).getTypeName());
			return ret;
		}

		public ArrayList<Boolean> getCheckStatus() {
			return checkStatus;
		}

		public void setCheckStatus(ArrayList<Boolean> checkStatus) {
			this.checkStatus = checkStatus;
		}
	}
	
	class ReasonsAdapter extends BaseAdapter {
		
		ArrayList<ConfigRefundReasonDTS> reasons = Globals.getInstance(getApplicationContext()).getRefundReasons();
		private ArrayList<Boolean> checkStatus = new ArrayList<Boolean>();
		
		public ReasonsAdapter() {
			for (int i = 0; i < reasons.size(); i++) {
				checkStatus.add(false);
			}
		}
		
		@Override
		public int getCount() {
			return reasons == null ? 0 : reasons.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_refund_types_list, null);
			} else {
				ret = arg1;
			}
			UIHelper.setText(ret, R.id.text, reasons.get(arg0).getReasonName());
			ret.findViewById(R.id.indicator).setSelected(checkStatus.get(arg0));
			return ret;
		}

		public ArrayList<Boolean> getCheckStatus() {
			return checkStatus;
		}

		public void setCheckStatus(ArrayList<Boolean> checkStatus) {
			this.checkStatus = checkStatus;
		}
	}
	
	public void refund(View view) {
		// TODO:
		ArrayList<Boolean> selectes = reasonsAdapter.getCheckStatus();
		ArrayList<ConfigRefundReasonDTS> reasons = Globals.getInstance(this).getRefundReasons();

		ArrayList<ConfigRefundReasonDTS> selected = new ArrayList<ConfigRefundReasonDTS>();
		for (int index = 0; index < reasons.size(); index ++) {
			if (selectes.get(index)) {
				selected.add(reasons.get(index));
			}
		}
		
		if (order == null) {
			UIHelper.showTips(submit, "订单加载失败");
			return;
		}
		
		if (selected.size() == 0) {
			UIHelper.showTips(submit, "至少选择一个退款理由");
			return;
		}
		
		String reasonsString = "" + selected.get(0).getId();
		for (int index = 1; index < selected.size(); index ++) {
			reasonsString += ("," + selected.get(index).getId());
		}
		final String reasonsStringfinal = reasonsString;
		
		ArrayList<ConfigRefundTypeDTS> refundTypes = Globals.getInstance(this).getRefundTypes();
		if (refundTypes == null || refundTypes.size() == 0) {
			UIHelper.showTips(submit, "还款类型不能为空");
			return;
		}
		final String typesString = "" + refundTypes.get(0).getId();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				UserLoginResponse ulRsp = UserLoginResponse.getInstance(RefundRequestActivity.this);
				JSONObject params = new JSONObject();
				try {
					params.put("orderId", order.getId());
					params.put("refundType", typesString);
					params.put("refundReason", reasonsStringfinal);
					params.put("refundFee", "" + order.getPayPrice());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ResponseObject code;
				try {
					 code = UserReg.requestRefundOrder(ulRsp, params, RefundRequestActivity.this);
					 mHandler.sendMessage(mHandler.obtainMessage(MSG_REFUND_DONE, code));
					 return;
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				mHandler.sendMessage(mHandler.obtainMessage(MSG_REFUND_DONE, new ResponseObject(-1, "")));
				return;
			}
		}).start();
		dialog = MyProgressDialog.show(this, "", "提交中...");
	}

	private void dismissDialogInternal() {
		if (dialog != null) {
			dialog.dismiss();
			dialog = null;
		}
	}
}
